/*
 * 百度在线网络技术（北京）有限公司拥有本软件版权2022并保留所有权利。
 * Copyright 2022, Baidu.com,Inc 2:Baidu Online Network Technology (Beijing) Co.,Ltd,
 * All rights reserved.
 */

package com.azdebugit.spring.docother.juc;

/**
 * @author azdebugit
 * Date 2021/7/3
 * @version 1.0
 * synchronized版生产者消费者
 */
public class Syn {
    public static void main(String[] args) {
        Data data = new Data();

        //线程1
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        //线程2
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();

        //线程3
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();

        //线程4
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();

    }
}

class Data {
    private int num;

    public int getNum() {
        return num;
    }

    //增加
    public synchronized void increment() throws InterruptedException {
        //判断等待
        //用while，不用if，防止虚假唤醒
        while (num != 0) {
            this.wait();
        }
        //业务代码
        num++;
        System.out.println(Thread.currentThread().getName() + "  -->  " + num);
        //通知
        this.notifyAll();
    }

    //减少
    public synchronized void decrement() throws InterruptedException {
        //判断等待
        //用while，不用if，防止虚假唤醒
        while (num == 0) {
            this.wait();
        }
        //业务代码
        num--;
        System.out.println(Thread.currentThread().getName() + "  -->  " + num);
        //通知
        this.notifyAll();
    }
}
